﻿using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using LanDBom.Models;
using LanDBom.Models.price_New_2;
using LanDBom.Models.Procure;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using static System.Windows.Forms.AxHost;

namespace LanDBom.Controllers
{
    public class CustomController : Controller
    {
        // GET: Custom
        Add_CL add_cl = new Add_CL();
        LDbaseEntities db = new LDbaseEntities();
        Find_BOMini mini = new Find_BOMini();
        Find_APP_information find_APP = new Find_APP_information();
        public ActionResult Custom(int state = 0)
        {
            if (state == 1)
            {
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BOS_ASSISTANTDATA_DETAIL";
                string fieldKeys = "FDataValue,FId.FName";//货币名称
                string Filter = "FId.FName in ('地区','国家','城市')";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 200,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(result, settings);

                return Content(jsongStr, "application/json");
            }
            return View();
        }

        public ActionResult AddClientele(Clirntele clirntele)
        {
            int rows = add_cl.AddClirntele(clirntele);
            string message = rows > 0 ? "添加成功" : "添加失败";
            return Content(message, "text / plain");
        }
        public ActionResult Profit(string names, string BOM2_wuLiu = "", string BOM2_liao = "", int state = 0, string Namesed = "", string liyou = "")
        {
            if (state == 0)
            {
                var applications = db.Applications.Where(s => s.AP_bian == names).ToList();
                var snif = db.Applications.Where(r => r.AP_bian == names).FirstOrDefault();
                var hdns = snif.App_BanB;
                var dhf = mini.B_findnext2(BOM2_wuLiu, BOM2_liao, names);
                dhf = dhf.OrderBy(s => s.BOM2_BQing).ToList();
                foreach (var d in applications)
                {
                    dhf = dhf.Where(p => p.BOM2_Zhuang == d.App_BanB).ToList();
                }
                ViewBag.F_bom = dhf;
                ViewBag.F_bomED = dhf;
                return View(applications);
            }

            if (state == 1)
            {
                var shuan = db.Applications.Where(s => s.AP_bian == names).FirstOrDefault();
                var shinf = double.Parse(shuan.App_BanB);
                var shifn = Math.Truncate(shinf) + 1;
                shuan.App_BanB = shifn.ToString();
                shuan.App_bu = "5";
                shuan.APP_liy = liyou;
                shuan.APP_shr = Namesed;
                int sun = db.SaveChanges();
                string message = "";
                if (sun > 0)
                {
                    int font = 0;
                    var BOmi = db.BOMini.Where(b => b.BOM2_bian == names && b.BOM2_Zhuang == shinf.ToString()).ToList();
                    foreach (var b in BOmi)
                    {
                        b.BOM2_Zhuang = shifn.ToString();
                        if (b.BOM2_sunhao == "已核价")
                        {
                            b.BOM2_sunhao = "已询价";
                        }
                        db.Entry(b).State = EntityState.Modified;
                        font += db.SaveChanges();
                    }
                    //添加驳回理有

                    var bohui = new BeiZhu()
                    {
                        B_Bian = names,
                        B_bei = liyou,
                        B_Date = DateTime.Now.ToString("yyyy/M/d"),
                        B_BR = Namesed,
                    };
                    db.BeiZhu.Add(bohui);
                    int IJK = db.SaveChanges();

                    var inf = db.Informa.Where(s => s.Inf_shen == names).ToList();
                    foreach (var item in inf)
                    {
                        item.Inf_zhuang = "已提交";
                        db.Entry(item).State = EntityState.Modified;
                        int hunns = db.SaveChanges();
                    }
                    message = font == BOmi.Count() ? "已驳回" : "修改失败";
                }
                else
                {
                    message = "系统报错！请重试";
                }
                return Content(message);

            }
            else if (state == 2)
            {
                var list1 = db.Informa.Where(x => x.Inf_shen == liyou).ToList();
                var list2 = db.BOMini.Where(x => x.BOM2_bian == liyou).ToList();
                var temp = from a in list1
                           join b in list2 on a.Inf_shen equals b.BOM2_bian into c
                           from d in c.DefaultIfEmpty()
                           select new { a.Inf_wu, a.Inf_huiP, a.Inf_gong, d.BOM2_mioa, a.Inf_JT };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // 处理循环引用  
                    Formatting = Formatting.Indented // 格式化输出，便于阅读  
                };
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 3)
            {
                var appedrr = db.Applications.Where(s => s.AP_bian == names).FirstOrDefault();
                var bom = db.BOMini.Where(s => s.BOM2_bian == appedrr.AP_bian && s.BOM2_Zhuang == appedrr.App_BanB && s.BOM2_chen == "Leve0").ToList();
                var lei = appedrr.App_lei;
                System.Data.DataTable dt = NewMethod();

                foreach (var item in bom)
                {

                    if (item.BOM2_CB != null)
                    {
                        var spl = item.BOM2_CB.Split(',');
                        if (spl != null)
                        {
                            for (int j = 0; j < spl.Length; j++)
                            {
                                if (spl[j] == "")
                                {
                                    continue;
                                }
                                var kom = spl[j].Split(':');
                                var jKONN = 0;//inf_id
                                var gys = "";//供应商
                                if (item.BOM2_Lei != "自制")
                                {
                                    var JNSMM = kom[0] == "" ? "-1" : kom[0];
                                    jKONN = int.Parse(JNSMM);//inf_id
                                    var gysss = db.Informa.Where(s => s.Inf_id == jKONN).FirstOrDefault();//供应商
                                    gys = gysss == null ? "" : gysss.Inf_gong;
                                }
                                var jiee = "";  //阶梯
                                if (kom.Length < 3)
                                {
                                    var s = item.BOM2_liao;
                                    var hu = db.Formation.Where(J => J.FM_bai == s).FirstOrDefault();
                                    if (hu == null)
                                    {
                                        jiee = "1";
                                    }
                                    else
                                    {
                                        var sh = hu.FM_Jieti.Split(',');
                                        jiee = sh[j];
                                    }
                                }
                                else
                                {
                                    jiee = kom[1];
                                }
                                var jieeed = kom.Length < 3 ? kom[0] : kom[2];  //价格
                                dt.Rows.Add(item.BOM2_id, gys, "", jieeed, item.BOM2_wuLiu, item.BOM2_ST, jiee, item.BOM2_liao, item.BOM2_Guige, item.BOM2_Sone, item.BOM2_Lei);  //
                            }
                        }
                    }

                }
                DataView dataView = dt.DefaultView;
                dataView.Sort = "BOM2_Jin";
                var dtCopy = dt.Copy();
                dtCopy = dataView.ToTable();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(dt, settings);
                return Content(jsongStr, "application/json");

            }
            else if (state == 4)
            {
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_Currency";
                string fieldKeys = "FName";//货币名称
                string Filter = "FDocumentStatus='C'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 200,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(result, settings);

                return Content(jsongStr, "application/json");
            }

            return View();
        }

        private static System.Data.DataTable NewMethod()
        {
            var dt = new System.Data.DataTable();
            dt.Columns.Add("BOM2_id", typeof(string));//编号
            dt.Columns.Add("BOM2_Gong", typeof(string));//供应商
            dt.Columns.Add("BOM2_mioa", typeof(string));//价格
            dt.Columns.Add("BOM2_CB", typeof(string));//成本
            dt.Columns.Add("BOM2_wuLiu", typeof(string));//物料名
            dt.Columns.Add("BOM2_ST", typeof(string));//二级类别
            dt.Columns.Add("BOM2_Jin", typeof(string));//阶梯
            dt.Columns.Add("BOM2_liao", typeof(string));//料号
            dt.Columns.Add("BOM2_Guige", typeof(string));//规格
            dt.Columns.Add("BOM2_Sone", typeof(string));//一级类别
            dt.Columns.Add("BOM2_Lei", typeof(string));//属性
            return dt;
        }

        public ActionResult General(string SHun, string AP_bian = "", string App_Kehu = "", string App_JTime = "", int states = 0, string XMfzr = "")
        {
            List<Applications> app = db.Applications.Where(s => s.AP_bian.Contains(AP_bian) && s.App_bu == SHun&&s.AP_QTJY==null).OrderByDescending(s => s.App_id).ToList();
            //屏蔽正在审核的单据
            var DANJU = new List<Applications>();
            foreach (var item in app)
            {
                var Bina = item.AP_bian;
                var HJ = db.shenpingliu.Where(s => s.FJINF == Bina && s.FMIao == "对外报价").FirstOrDefault();
                if (HJ == null || HJ.FFZ == "驳回")
                {
                    DANJU.Add(item);
                }
            }
            ViewBag.C_App = DANJU;
            var listApp = find_APP.find_app_infor11(AP_bian, App_Kehu, App_JTime, XMfzr);
            if (states == 1)
            {
                var list = from s in listApp
                           select new { s.App_id, s.App_Kehu, s.App_qishi, s.App_JTime, s.AP_bian, s.APP_name, s.App_bu, s.APP_fenL, s.App_zhand, s.AP_ren, s.App_fzr };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        [HttpPost]
        public JsonResult AddAppli(List<Informa> bOMinis)
        {
            string sun = "";
            try
            {
                var lisgyjn = new List<BOMini>();
                var shun = "";
                for (int i = 0; i < bOMinis.Count; i++)
                {
                    var shuLPPn = bOMinis[i].BOM2_id;//BOMID的值
                    if (shun == shuLPPn.ToString())
                    {
                        continue;
                    }
                    else
                    {
                        var shund = bOMinis.Where(s => s.BOM2_id == shuLPPn).ToList();
                        var jinskkf = "";
                        var jinskkf1 = "";
                        for (int k = 0; k < shund.Count; k++)
                        {
                            var miao = shund[k].Inf_JT + ":" + shund[k].Inf_huiP + ",";//编码属性：阶梯：价格
                            var miao1 = shund[k].Inf_JT + ":" + shund[k].Inf_gong + ",";//编码属性：阶梯：价格
                            jinskkf += miao;
                            jinskkf1 += miao1;
                        }
                        var bom = new BOMini();
                        bom.BOM2_id = (int)shuLPPn;
                        bom.BOM2_mioa = jinskkf;
                        bom.BOM2_Jin = jinskkf1;
                        lisgyjn.Add(bom);
                    }
                }
                int shhh = 0;
                foreach (BOMini b in lisgyjn)
                {
                    var isde = b.BOM2_id;
                    var shudij = db.BOMini.FirstOrDefault(s => s.BOM2_id == isde);//BOM行
                    shudij.BOM2_mioa = b.BOM2_mioa;
                    shudij.BOM2_Jin = b.BOM2_Jin;
                    db.Entry(shudij).State = EntityState.Modified;
                    shhh += db.SaveChanges();
                }
                if (shhh == lisgyjn.Count)
                {
                    /* var app = db.Applications.FirstOrDefault(s => s.AP_bian == shunf);
                     app.App_bu = "7";
                     db.Entry(app).State = EntityState.Modified;
                     int sj = db.SaveChanges();*/
                    sun = "利润保存成功！";
                }
                else
                {
                    sun = "利润保存失败！";
                }
            }
            catch (Exception)
            {

                throw;
            }

            return Json(sun);
        }

        // GET: Formations/Edit/5
        public ActionResult ViewEdit(int? id, int state = 0)
        {
            if (id != 0 && id != null)
            {
                Session["CL_id"] = id;
            }
            if (state == 1)
            {
                var shun = db.Clirntele.Where(s => s.CL_ID == id).FirstOrDefault();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(shun, settings);

                return Content(jsongStr, "application/json");
            }
            return View();
        }
    }

}